<?php

class Ahs_Validators_UserEmail extends Zend_Validate_Abstract
{
    const INV_EMAIL     = 'emailNotValid';
    const INV_TYPEID    = 'typeIdNotValid';

    protected $_messageTemplates = array(
        self::INV_EMAIL     => 'This e-mail is invalid',
        self::INV_TYPEID    => 'Please select a type',
    );

    protected $_field_email     = "";
    protected $_field_type_id   = "";

    public function __construct($values = array())
    {
        $this->setValues($values);
    }
    
    public function setValues($values = array())
    {
        if(is_array($values) && count($values) == 3)
        {
            $this->_field_email = $values[1];
            $this->_field_type_id = $values[2];
        }
    }

    public function isValid($value, $context = null)
    {
        /**
         * @todo VALIDATION -- Check if email already exists in database on registration. If user is logged in, check the email while ignoring the current email's ID. 
         */
        $values = explode("*", $value);
        $this->setValues($values);
        
        $value = (string) $value;
        $this->_setValue($value);

        $error = false;
        $validMail = $ValidID = "V";
        
        // Validate the E-mail
        $EmailValidator = new Zend_Validate_EmailAddress();
        if(!$EmailValidator->isValid($this->_field_email))
        {
            $error = true;
            $validMail  = "X";
            $this->_error(self::INV_EMAIL);
        }
        
        // Validate the Type ID
        if(!preg_match("/^[1-9][0-9]*$/", $this->_field_type_id))
        {
            $error = true;
            $ValidID    = "X";
            $this->_error(self::INV_TYPEID);
        }

        return !$error;
    }
}
